/*
 * @Description: MCU STD
 * @Author: diyhome
 * @Date: 2020-12-26 22:00
 * @File: mcu_std
*/

#include <cstdio>
#include "mcu_std.h"
namespace mcu_std {
    char *endl = "\n";
}

void mcu_std::_cout::__printf(char *pdata) const {
    int length = 0;
    char *temp = pdata;
    while(*temp++) length++;
    HAL_UART_Transmit(this->uart_handle,(uint8_t *)pdata,length,0xff);
// DMA进入中断之后回调会出现一些问题
//    HAL_UART_Transmit_DMA(this->uart_handle,(uint8_t *)pdata,length);
}

const mcu_std::_cout &mcu_std::_cout::operator<<(const int integer) const {
#ifdef ENABLE_NEW_DELETE
    char *temp = new char;
    sprintf(temp,"%d",integer);
    this->printf(temp);
    delete temp;
#else
    int temp[LENGTH_CHAR] = {0};
    int num = integer, index = 0;
    do {
        temp[index] = num % 10;
        num /= 10;
        index++;
    } while (num);

    char str[LENGTH_CHAR] = {0};
    for(int i = 0, j = index - 1; i < index; i++, j--){
        str[i] = (char)(temp[j] + 48);
    }
    this->__printf(str);
#endif
    return *this;
}

const mcu_std::_cout &mcu_std::_cout::operator<<(const char *s) const {
    this->__printf((char *) s);
    return *this;
}

const mcu_std::_cout &mcu_std::_cout::operator<<(const float integer) const {
#ifdef ENABLE_NEW_DELETE
    char *temp = new char;
    sprintf(temp, "%f", integer);
    this->printf(temp);
    delete temp;
#else
    char temp[LENGTH_CHAR];
    sprintf(temp,"%f",integer);
    this->__printf(temp);
#endif
    return *this;
}

const mcu_std::_cout &mcu_std::_cout::operator<<(double integer) const {
#ifdef ENABLE_NEW_DELETE
    char *temp = new char;
    sprintf(temp, "%f", integer);
    this->printf(temp);
    delete temp;
#else
    char temp[LENGTH_CHAR];
    sprintf(temp,"%f",integer);
    this->__printf(temp);
#endif
    return *this;
}
